import { ElMessage } from 'element-plus';
import axios from 'axios';
import { clearToken, getToken, setToken } from '@/utils/auth';

export const BASE_NAME = import.meta.env.VITE_BASE_NAME_API;
export const BASE_NAME_SWDYX = import.meta.env.VITE_BASE_NAME_API_XT;

export const CURRENT_CONFIG = {
  VITE_APP_NAME: import.meta.env.VITE_APP_NAME,
  VITE_LOGIN_NAME: import.meta.env.VITE_LOGIN_NAME,
};

// 访问前缀（线下）
export const BASE_MATTER_MAP_URL = 'https://www.xazrhh.com:1443/matterServerAlpha/#/login';
export const BASE_NAME_MAP = '/st_server_api_v2';
export const BASE_GEOSERVER_URL = 'https://www.xazrhh.com:1443';
// 响应码
export const ResponseSuccessCode = '00000';
export const ResponseCode = [
  {
    code: '00000',
    msg: '操作成功',
  },
  {
    code: 'A0001',
    msg: '未认证',
  },
  {
    cole: 'A0002',
    msg: '无权限',
  },
  {
    code: 'A0003',
    msg: '无效token',
  },
  {
    code: 'A0005',
    msg: '用户名不存在',
  },
  {
    code: 'A0004',
    msg: '刷新token与认证token不匹配',
  },
  {
    code: 'A0007',
    msg: '密码错误次数过多,请5分钟后再试',
  },
  {
    code: 'A0006',
    msg: '密码不正确',
  },
  {
    code: 'A1001',
    msg: '用户名已存在',
  },
  {
    code: 'A0101',
    msg: '参数错误',
  },
  {
    code: 'A1003',
    msg: '用户不存在',
  },
  {
    code: 'A1002',
    msg: '手机号已存在',
  },
  {
    code: 'A1101',
    msg: '角色不存在',
  },
  {
    code: 'A1102',
    msg: '存在用户绑定了角色，无法删除',
  },
  {
    code: 'A1202',
    msg: '',
  },
  {
    code: 'A1201',
    msg: '权限不存在',
  },
  {
    code: 'A1004',
    msg: '原密码不正确',
  },
  {
    code: 'A1302',
    msg: '组织不为空，无法删除',
  },
  {
    code: 'A2001',
    msg: '中文学名已存在',
  },
];

const http = axios.create({
  // timeout: 5000,
});

// 文件上传头
export const getFileHeaders = () => {
  return {
    Authorization: getToken() ? `Bearer ${getToken()}` : '',
    'CUSTOMIZE-CLIENT-TYPE': 'web',
  };
};

// let isExpire = false;
let isRefreshing = false;
let refreshSubscribers = []; // 存储等待刷新完成的请求

/**
 *无感刷新Token方法
 *
 */
// function refreshFn(tokenInfo) {
//   const { expireTime, accessToken, refreshToken } = JSON.parse(tokenInfo);
//   const remainTime = 10 * 60 * 1000;

//   if (expireTime - remainTime < Date.now() && expireTime > Date.now()) {
//     if (!isExpire) {
//       isExpire = true;
//       axios
//         .post(`${BASE_NAME}/api/auth/refresh`, { accessToken, refreshToken })
//         .then((res) => {
//           const { data } = res.data;

//           localStorage.setItem(
//             'tokenInfo',
//             JSON.stringify({
//               ...data,
//               expireTime: Date.now() + data.expireIn,
//             }),
//           );
//           setToken(data.accessToken, true);
//         })
//         .finally(() => {
//           isExpire = false;
//         });
//     }
//   }
// }

// 订阅刷新完成后的回调
function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}

// 通知所有等待的请求，刷新完成
function onRefreshed(newToken) {
  refreshSubscribers.forEach((cb) => cb(newToken));
  refreshSubscribers = [];
}

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = getToken();

    config.headers.Authorization = token ? `Bearer ${token}` : '';

    return config;
  },
  (error) => Promise.reject(error),
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    if (response.headers['content-type'] === 'application/json') {
      return response.data;
    }

    return response;
  },
  async (error) => {
    const { response } = error;
    const config = response?.config;

    // 避免循环刷新
    if (config.url === '/api/auth/refresh') {
      clearToken();
      location.assign(`${import.meta.env.VITE_BASE_PATH}/#/login`);

      return Promise.reject(error);
    }

    const resCode = response?.data?.code;

    if (['A0001', 'A0003'].includes(resCode)) {
      // Token 过期或无效，尝试无感刷新
      if (!isRefreshing) {
        isRefreshing = true;

        try {
          const tokenInfo = localStorage.getItem('tokenInfo');

          if (!tokenInfo) {
            clearToken();
            location.assign(`${import.meta.env.VITE_BASE_PATH}/#/login`);

            return Promise.reject(error);
          }

          const { accessToken, refreshToken } = JSON.parse(tokenInfo);

          const refreshRes = await axios.post(`${BASE_NAME}/api/auth/refresh`, {
            accessToken,
            refreshToken,
          });

          const { data } = refreshRes.data;

          if (data?.accessToken) {
            const newToken = data.accessToken;
            const expireTime = Date.now() + data.expireIn;

            localStorage.setItem('tokenInfo', JSON.stringify({ ...data, expireTime }));
            setToken(newToken, true);

            // 通知所有等待的请求，刷新完成
            onRefreshed(newToken);

            // 重新设置当前请求的 token
            config.headers.Authorization = `Bearer ${newToken}`;

            return http(config); // 重试原请求
          }
        } catch (refreshError) {
          clearToken();
          location.assign(`${import.meta.env.VITE_BASE_PATH}/#/login`);

          return Promise.reject(refreshError);
        } finally {
          isRefreshing = false;
          refreshSubscribers = [];
        }
      }

      // 如果正在刷新，把当前请求挂起，等待刷新完成
      return new Promise((resolve) => {
        subscribeTokenRefresh((newToken) => {
          config.headers.Authorization = `Bearer ${newToken}`;
          resolve(http(config));
        });
      });
    }

    // 其他错误处理
    if (response?.status === 500) {
      ElMessage.error('服务器内部错误');
    } else if (response?.status === 404) {
      ElMessage.error('接口地址错误');
    } else if (response?.data?.message) {
      // 排除未认证类错误，避免重复提示
      if (!['A0001', 'A0002', 'A0003'].includes(resCode)) {
        ElMessage.error(response.data.message);
      }
    }

    return Promise.reject(response?.data || error);
  },
);

export default http;
